import { Router } from 'express';
import { body, param, query } from 'express-validator';
import { authenticateToken, authorizeRole } from '../middleware/auth';
import { validateRequest } from '../middleware/validation';
import { generateSlug } from '../lib/utils';
import { prisma } from '../lib/prisma';

const router = Router();

// 获取知识库列表
router.get('/', 
  authenticateToken,
  [
    query('page').optional().isInt({ min: 1 }).withMessage('页码必须是正整数'),
    query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('每页数量必须在1-100之间'),
    query('search').optional().isString().trim(),
    query('status').optional().isIn(['DRAFT', 'PUBLISHED', 'ARCHIVED']),
    query('categoryId').optional().isString(),
    query('tagIds').optional().isString(),
    query('authorId').optional().isString(),
    query('featured').optional().isBoolean()
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { 
        page = 1, 
        limit = 20, 
        search, 
        status, 
        categoryId, 
        tagIds, 
        authorId,
        featured 
      } = req.query;
      const skip = (Number(page) - 1) * Number(limit);

      // 构建查询条件
      const where: any = {};
      if (search) {
        where.OR = [
          { title: { contains: search as string, mode: 'insensitive' } },
          { description: { contains: search as string, mode: 'insensitive' } },
          { content: { contains: search as string, mode: 'insensitive' } }
        ];
      }
      if (status) where.status = status;
      if (categoryId) where.categoryId = categoryId;
      if (authorId) where.authorId = authorId;
      if (featured !== undefined) where.featured = featured === 'true';

      // 处理标签筛选
      if (tagIds) {
        const tagIdArray = (tagIds as string).split(',');
        where.tags = {
          some: {
            id: { in: tagIdArray }
          }
        };
      }

      // 查询知识库
      const [knowledgeBases, total] = await Promise.all([
        prisma.knowledgeBase.findMany({
          where,
          select: {
            id: true,
            title: true,
            description: true,
            slug: true,
            excerpt: true,
            status: true,
            featured: true,
            viewCount: true,
            likeCount: true,
            publishedAt: true,
            createdAt: true,
            updatedAt: true,
            author: {
              select: {
                id: true,
                username: true,
                avatar: true
              }
            },
            category: {
              select: {
                id: true,
                name: true,
                color: true
              }
            },
            tags: {
              select: {
                id: true,
                name: true,
                color: true
              }
            },
            _count: {
              select: {
                likes: true,
                comments: true
              }
            }
          },
          skip,
          take: Number(limit),
          orderBy: { createdAt: 'desc' }
        }),
        prisma.knowledgeBase.count({ where })
      ]);

      res.json({
        code: 200,
        message: '获取知识库列表成功',
        data: {
          knowledgeBases,
          pagination: {
            page: Number(page),
            limit: Number(limit),
            total,
            pages: Math.ceil(total / Number(limit))
          }
        }
      });
    } catch (error) {
      console.error('获取知识库列表失败:', error);
      res.status(500).json({ success: false, error: '获取知识库列表失败' });
    }
  }
);

// 获取单个知识库
router.get('/:id',
  authenticateToken,
  [
    param('id').isString().notEmpty().withMessage('知识库ID不能为空')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { id } = req.params;
      const knowledgeBase = await prisma.knowledgeBase.findUnique({
        where: { id },
        select: {
          id: true,
          title: true,
          description: true,
          content: true,
          slug: true,
          excerpt: true,
          status: true,
          featured: true,
          viewCount: true,
          likeCount: true,
          publishedAt: true,
          createdAt: true,
          updatedAt: true,
          author: {
            select: {
              id: true,
              username: true,
              avatar: true
            }
          },
          category: {
            select: {
              id: true,
              name: true,
              description: true,
              color: true
            }
          },
          tags: {
            select: {
              id: true,
              name: true,
              description: true,
              color: true
            }
          },
          likes: {
            select: {
              user: {
                select: {
                  id: true,
                  username: true,
                  avatar: true
                }
              }
            }
          },
          comments: {
            where: { status: 'APPROVED' },
            select: {
              id: true,
              content: true,
              createdAt: true,
              author: {
                select: {
                  id: true,
                  username: true,
                  avatar: true
                }
              }
            },
            orderBy: { createdAt: 'desc' }
          }
        }
      });

      if (!knowledgeBase) {
        return res.status(404).json({ success: false, error: '知识库不存在' });
      }

      // 增加浏览次数
      await prisma.knowledgeBase.update({
        where: { id },
        data: { viewCount: { increment: 1 } }
      });

      res.json({ code: 200, message: '获取知识库详情成功', data: knowledgeBase });
    } catch (error) {
      console.error('获取知识库详情失败:', error);
      res.status(500).json({ success: false, error: '获取知识库详情失败' });
    }
  }
);

// 创建知识库
router.post('/',
  authenticateToken,
  authorizeRole(['ADMIN', 'EDITOR']),
  [
    body('title').isString().trim().isLength({ min: 1, max: 200 }).withMessage('标题长度必须在1-200个字符之间'),
    body('description').optional().isString().trim(),
    body('content').isString().trim().isLength({ min: 1 }).withMessage('内容不能为空'),
    body('categoryId').optional().isString(),
    body('tagIds').optional().isArray(),
    body('status').optional().isIn(['DRAFT', 'PUBLISHED']).withMessage('状态无效'),
    body('featured').optional().isBoolean()
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { 
        title, 
        description, 
        content, 
        categoryId, 
        tagIds = [], 
        status = 'DRAFT',
        featured = false 
      } = req.body;

      // 生成slug
      const slug = await generateSlug(title, 'knowledgeBase');

      // 创建知识库
      const knowledgeBase = await prisma.knowledgeBase.create({
        data: {
          title,
          description,
          content,
          slug,
          excerpt: description ? description.substring(0, 200) : content.substring(0, 200),
          status,
          featured,
          publishedAt: status === 'PUBLISHED' ? new Date() : null,
          authorId: req.user.id,
          categoryId: categoryId || null,
          tags: {
            connect: tagIds.map((id: string) => ({ id }))
          }
        },
        select: {
          id: true,
          title: true,
          slug: true,
          status: true,
          createdAt: true
        }
      });

      res.status(201).json({ code: 200, message: '知识库创建成功', data: knowledgeBase });
    } catch (error) {
      console.error('创建知识库失败:', error);
      res.status(500).json({ success: false, error: '创建知识库失败' });
    }
  }
);

// 更新知识库
router.put('/:id',
  authenticateToken,
  authorizeRole(['ADMIN', 'EDITOR']),
  [
    param('id').isString().notEmpty().withMessage('知识库ID不能为空'),
    body('title').optional().isString().trim().isLength({ min: 1, max: 200 }).withMessage('标题长度必须在1-200个字符之间'),
    body('description').optional().isString().trim(),
    body('content').optional().isString().trim(),
    body('categoryId').optional().isString(),
    body('tagIds').optional().isArray(),
    body('status').optional().isIn(['DRAFT', 'PUBLISHED', 'ARCHIVED']).withMessage('状态无效'),
    body('featured').optional().isBoolean()
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { id } = req.params;
      const updateData = req.body;

      // 检查知识库是否存在
      const existingKnowledgeBase = await prisma.knowledgeBase.findUnique({ 
        where: { id },
        select: { authorId: true, status: true }
      });
      
      if (!existingKnowledgeBase) {
        return res.status(404).json({ success: false, error: '知识库不存在' });
      }

      // 检查权限（编辑者只能编辑自己的文章，管理员可以编辑所有）
      if (req.user.role !== 'ADMIN' && existingKnowledgeBase.authorId !== req.user.id) {
        return res.status(403).json({ success: false, error: '没有权限编辑此知识库' });
      }

      // 如果更新标题，重新生成slug
      if (updateData.title) {
        updateData.slug = await generateSlug(updateData.title, 'knowledgeBase', id);
      }

      // 如果更新内容或描述，更新摘要
      if (updateData.content || updateData.description) {
        updateData.excerpt = updateData.description 
          ? updateData.description.substring(0, 200) 
          : updateData.content.substring(0, 200);
      }

      // 如果状态改为已发布，设置发布时间
      if (updateData.status === 'PUBLISHED' && existingKnowledgeBase.status !== 'PUBLISHED') {
        updateData.publishedAt = new Date();
      }

      // 更新知识库
      const knowledgeBase = await prisma.knowledgeBase.update({
        where: { id },
        data: {
          ...updateData,
          tags: updateData.tagIds ? {
            set: updateData.tagIds.map((tagId: string) => ({ id: tagId }))
          } : undefined
        },
        select: {
          id: true,
          title: true,
          slug: true,
          status: true,
          updatedAt: true
        }
      });

      res.json({ code: 200, message: '知识库更新成功', data: knowledgeBase });
    } catch (error) {
      console.error('更新知识库失败:', error);
      res.status(500).json({ success: false, error: '更新知识库失败' });
    }
  }
);

// 删除知识库
router.delete('/:id',
  authenticateToken,
  authorizeRole(['ADMIN', 'EDITOR']),
  [
    param('id').isString().notEmpty().withMessage('知识库ID不能为空')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { id } = req.params;

      // 检查知识库是否存在
      const existingKnowledgeBase = await prisma.knowledgeBase.findUnique({ 
        where: { id },
        select: { authorId: true }
      });
      
      if (!existingKnowledgeBase) {
        return res.status(404).json({ success: false, error: '知识库不存在' });
      }

      // 检查权限
      if (req.user.role !== 'ADMIN' && existingKnowledgeBase.authorId !== req.user.id) {
        return res.status(403).json({ success: false, error: '没有权限删除此知识库' });
      }

      // 删除知识库（级联删除相关数据）
      await prisma.knowledgeBase.delete({ where: { id } });

      res.json({ code: 200, message: '知识库删除成功', data: null });
    } catch (error) {
      console.error('删除知识库失败:', error);
      res.status(500).json({ success: false, error: '删除知识库失败' });
    }
  }
);

// 切换知识库状态
router.patch('/:id/status',
  authenticateToken,
  authorizeRole(['ADMIN', 'EDITOR']),
  [
    param('id').isString().notEmpty().withMessage('知识库ID不能为空'),
    body('status').isIn(['DRAFT', 'PUBLISHED', 'ARCHIVED']).withMessage('状态无效')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { id } = req.params;
      const { status } = req.body;

      // 检查知识库是否存在
      const existingKnowledgeBase = await prisma.knowledgeBase.findUnique({ 
        where: { id },
        select: { authorId: true }
      });
      
      if (!existingKnowledgeBase) {
        return res.status(404).json({ success: false, error: '知识库不存在' });
      }

      // 检查权限
      if (req.user.role !== 'ADMIN' && existingKnowledgeBase.authorId !== req.user.id) {
        return res.status(403).json({ success: false, error: '没有权限修改此知识库' });
      }

      // 更新状态
      const updateData: any = { status };
      if (status === 'PUBLISHED') {
        updateData.publishedAt = new Date();
      }

      const knowledgeBase = await prisma.knowledgeBase.update({
        where: { id },
        data: updateData,
        select: {
          id: true,
          title: true,
          status: true,
          publishedAt: true,
          updatedAt: true
        }
      });

      res.json({ code: 200, message: '知识库状态更新成功', data: knowledgeBase });
    } catch (error) {
      console.error('更新知识库状态失败:', error);
      res.status(500).json({ success: false, error: '更新知识库状态失败' });
    }
  }
);

// 切换精选状态
router.patch('/:id/featured',
  authenticateToken,
  authorizeRole(['ADMIN']),
  [
    param('id').isString().notEmpty().withMessage('知识库ID不能为空'),
    body('featured').isBoolean().withMessage('精选状态必须是布尔值')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { id } = req.params;
      const { featured } = req.body;

      // 检查知识库是否存在
      const existingKnowledgeBase = await prisma.knowledgeBase.findUnique({ where: { id } });
      if (!existingKnowledgeBase) {
        return res.status(404).json({ success: false, error: '知识库不存在' });
      }

      // 更新精选状态
      const knowledgeBase = await prisma.knowledgeBase.update({
        where: { id },
        data: { featured },
        select: {
          id: true,
          title: true,
          featured: true,
          updatedAt: true
        }
      });

      res.json({ code: 200, message: '精选状态更新成功', data: knowledgeBase });
    } catch (error) {
      console.error('更新精选状态失败:', error);
      res.status(500).json({ success: false, error: '更新精选状态失败' });
    }
  }
);

// 点赞/取消点赞
router.post('/:id/like',
  authenticateToken,
  [
    param('id').isString().notEmpty().withMessage('知识库ID不能为空')
  ],
  validateRequest,
  async (req, res) => {
    try {
      const { id } = req.params;
      const userId = req.user.id;

      // 检查知识库是否存在
      const existingKnowledgeBase = await prisma.knowledgeBase.findUnique({ where: { id } });
      if (!existingKnowledgeBase) {
        return res.status(404).json({ success: false, error: '知识库不存在' });
      }

      // 检查是否已经点赞
      const existingLike = await prisma.userLike.findUnique({
        where: {
          userId_knowledgeBaseId: {
            userId,
            knowledgeBaseId: id
          }
        }
      });

      if (existingLike) {
        // 取消点赞
        await Promise.all([
          prisma.userLike.delete({
            where: {
              userId_knowledgeBaseId: {
                userId,
                knowledgeBaseId: id
              }
            }
          }),
          prisma.knowledgeBase.update({
            where: { id },
            data: { likeCount: { decrement: 1 } }
          })
        ]);

        res.json({ code: 200, message: '取消点赞成功', data: { liked: false } });
      } else {
        // 添加点赞
        await Promise.all([
          prisma.userLike.create({
            data: {
              userId,
              knowledgeBaseId: id
            }
          }),
          prisma.knowledgeBase.update({
            where: { id },
            data: { likeCount: { increment: 1 } }
          })
        ]);

        res.json({ code: 200, message: '点赞成功', data: { liked: true } });
      }
    } catch (error) {
      console.error('点赞操作失败:', error);
      res.status(500).json({ success: false, error: '点赞操作失败' });
    }
  }
);

// 获取知识库统计信息
router.get('/stats/overview',
  authenticateToken,
  authorizeRole(['ADMIN']),
  async (req, res) => {
    try {
      const [
        totalKnowledgeBases,
        publishedKnowledgeBases,
        draftKnowledgeBases,
        featuredKnowledgeBases,
        totalViews,
        totalLikes,
        recentKnowledgeBases
      ] = await Promise.all([
        prisma.knowledgeBase.count(),
        prisma.knowledgeBase.count({ where: { status: 'PUBLISHED' } }),
        prisma.knowledgeBase.count({ where: { status: 'DRAFT' } }),
        prisma.knowledgeBase.count({ where: { featured: true } }),
        prisma.knowledgeBase.aggregate({
          _sum: { viewCount: true }
        }),
        prisma.knowledgeBase.aggregate({
          _sum: { likeCount: true }
        }),
        prisma.knowledgeBase.findMany({
          select: {
            id: true,
            title: true,
            status: true,
            viewCount: true,
            likeCount: true,
            createdAt: true
          },
          orderBy: { createdAt: 'desc' },
          take: 5
        })
      ]);

      res.json({
        code: 200,
        message: '获取知识库统计成功',
        data: {
          totalKnowledgeBases,
          publishedKnowledgeBases,
          draftKnowledgeBases,
          featuredKnowledgeBases,
          totalViews: totalViews._sum.viewCount || 0,
          totalLikes: totalLikes._sum.likeCount || 0,
          recentKnowledgeBases
        }
      });
    } catch (error) {
      console.error('获取知识库统计失败:', error);
      res.status(500).json({ success: false, error: '获取知识库统计失败' });
    }
  }
);

export { router as knowledgeBaseRoutes };
